//
//  MYHttp.m
//  Stock_Stategy
//
//  Created by MayerF on 2017/12/8.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "MYHttp.h"
#import "MYRC4.h"
#import <CommonCrypto/CommonDigest.h>

static unsigned char r[CC_MD5_DIGEST_LENGTH];

#define         RC4KEY "\x61\x83\x00\x91\x52\x21\x82\x3e\xe2\xa7\x75\xb6\x79\x71\xd8\x35"

static MYHttp *pHttp;

@interface MYHttp()

@end

@implementation MYHttp

+ (instancetype)shareHttpRequest
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        pHttp = [[MYHttp alloc] init];
    });
    return pHttp;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        //生产rc4秘钥
        [self packageInterMD5WithKey:@"hztczgxt"];
    }
    return self;
}

+ (NSURLSessionConfiguration *)configSession
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.timeoutIntervalForRequest = 15;
    config.allowsCellularAccess = YES;
    return config;
}

+ (void)post:(NSString *)url
      params:(id)params
     success:(void(^)(id response))success
     failure:(void(^)(NSError *error))failure
{
    [MYHttp shareHttpRequest];

    // json序列化
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSMutableString *resultStr = [NSMutableString stringWithString:jsonStr];
    // 去掉json串中的空格
    [resultStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, jsonStr.length)];
    // 去掉json串中的换行
    [resultStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, resultStr.length)];
    // 要求对json串直接加密
    char *charData = (char *)[resultStr UTF8String];
    NSInteger nLength = strlen(charData);
    // rc4加密
    char *pEnCode = EnDeCrypt(charData, (int)nLength, (char *)r, 16);
    NSData *newData = [NSData dataWithBytes:pEnCode length:nLength];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"%lu",(unsigned long)jsonData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:newData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            if (error) {
                failure(error);
                return;
            }
            if (data) {
                // 解密
                char *pDeCode = EnDeCrypt((char *)data.bytes, (int)data.length, (char *)r, 16);
                NSData *newData = [NSData dataWithBytes:pDeCode length:data.length];
                id obj = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableContainers error:nil];
                
                // 针对当前接口
                if ([obj isKindOfClass:[NSArray class]]) {
                    NSArray *array = (NSArray *)obj;
                    NSDictionary *dict = [array firstObject];
                    if ([dict.allKeys containsObject:@"code"]) {
                        
                        NSInteger code = [[dict valueForKey:@"code"] integerValue];
                        id result = nil;
                        if ([dict.allKeys containsObject:@"result"]) {
                            result = [dict valueForKey:@"result"];
                        }
        
                        if (code == 0) {
                            if (success) {
                                if ([result isEqual:[NSNull null]]) {
                                    success(nil);
                                }else {
                                    success(result);
                                }
                            }
                        }else if([dict.allKeys containsObject:@"msg"]){
                            
                            NSString *pMsg = [dict valueForKey:@"msg"];
                            NSError *pError = [NSError errorWithDomain:pMsg code:code userInfo:nil];
                            if (failure) {
                                failure(pError);
                            }
                        }
                    }else {
                        if (success) {
                            success(obj);
                        }
                    }
                    
                }else {
                    success(obj);
                }
            }
        });
    }];
    
    [task resume];
}

// md5加密key
- (NSString *)cryptoMD5WithKey:(NSString *)key
{
    const char *str = key.UTF8String;
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                          r[11], r[12], r[13], r[14], r[15]];
    return filename;
}
- (void)packageInterMD5WithKey:(NSString *)key
{
    const char *str = key.UTF8String;
    if (str == NULL) {
        str = "";
    }
    CC_MD5(str, (CC_LONG)strlen(str), r);
}

@end
